<!-- 权限管理 -->
<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { Expand as IconExpand, Fold as IconFold } from '@element-plus/icons-vue'
import type { IDbAction, IDbTable, ITagData } from '@/types/global'
import useNotic from '@/hooks/useNotic'
import DuiTable from '@/common-ui/dui-table/index.vue'
import * as authApi from '@/api/auth'
import { ENUM_AUTH_TYPE } from '@/config/enum'
import { ENUM_BTN_AUTH_SYS } from '@/config/btn'
import { useAuthStore } from '@/stores/auth'
import AuthInfo from './comps/AuthInfo.vue'
import { MENU_HIDDEN_LIST, MENU_STATUS_LIST, MENU_TYPE_LIST } from './config'

const authStore = useAuthStore()
// 权限数据-扁平结构
let menuList: any[] = []
// 表格数据
const tableRef = ref<InstanceType<typeof DuiTable>>()
const tableData = reactive<IDbTable>({
  data: [],
  columns: [
    { label: '名称', prop: 'title', align: 'left', minWidth: '200px' },
    {
      label: '类型',
      prop: 'type',
      width: '100px',
      type: 'tag',
      tagFunc: (scoped) => {
        const curStatus = MENU_TYPE_LIST.find((item) => item.value == scoped.row.type)
        const params: ITagData = { label: curStatus?.label || '', type: curStatus?.tagType || '' }
        return params
      }
    },
    { label: '描述', prop: 'description', width: '200px' },
    { label: '地址', prop: 'path', width: '100px' },
    { label: '权限字符', prop: 'apiUri', width: '200px' },
    {
      label: '启用状态',
      prop: 'status',
      width: '100px',
      type: 'tag',
      tagFunc: (scoped) => {
        const curStatus = MENU_STATUS_LIST.find((item) => item.value == scoped.row.status)
        const params: ITagData = { label: curStatus?.label || '', type: curStatus?.tagType || '' }
        return params
      }
    },
    {
      label: '是否隐藏菜单',
      prop: 'hidden',
      width: '120px',
      type: 'tag',
      tagFunc: (scoped) => {
        const curStatus = MENU_HIDDEN_LIST.find((item) => item.value == scoped.row.hidden)
        const params: ITagData = { label: curStatus?.label || '', type: curStatus?.tagType || '' }
        return params
      }
    },
    { label: '排序', prop: 'weigh', width: '60px' },
    { label: '操作', prop: 'handle', type: 'slot', fixed: 'right', width: '150px' }
  ]
})
// 弹窗数据
const AuthInfoRef = ref<InstanceType<typeof AuthInfo>>()
const dialogData = reactive({
  title: '', // 弹窗标题
  disabled: false // 是否禁用弹窗编辑
})

getDataList()

/**
 * 设置按钮列表
 */
function setBtnList(scoped: any) {
  let showAddBtn = false
  const addAuth = authStore.btnList.find((item) => item.value == ENUM_BTN_AUTH_SYS['权限:增'])
  if (scoped.row.type != ENUM_AUTH_TYPE['按钮'] && addAuth && addAuth.show) {
    showAddBtn = true
  }

  const list: IDbAction[] = [
    {
      label: '添加',
      type: 'primary',
      show: showAddBtn,
      onClick: () => addChildClick(scoped.row)
    },
    { label: '详情', type: 'primary', auth: ENUM_BTN_AUTH_SYS['权限:查'], onClick: () => infoClick(scoped.row, true) },

    { label: '编辑', type: 'primary', auth: ENUM_BTN_AUTH_SYS['权限:改'], onClick: () => infoClick(scoped.row, false) },
    { label: '删除', type: 'danger', auth: ENUM_BTN_AUTH_SYS['权限:删'], onClick: () => delClick(scoped) }
  ]
  return list
}
/**
 * 点击添加
 */
function addClick() {
  dialogData.title = '添加权限'
  dialogData.disabled = false
  const params = { pname: '主类目', pid: 0, ptype: ENUM_AUTH_TYPE['目录'] }
  AuthInfoRef.value?.init(params)
}
/**
 * 点击具体类目添加
 */
function addChildClick(row: any) {
  dialogData.title = '添加权限'
  dialogData.disabled = false
  AuthInfoRef.value?.init({ pname: row.title, pid: row.id, ptype: row.type })
}
/**
 * 点击详情/编辑
 */
function infoClick(row: any, disabled: boolean) {
  dialogData.title = disabled ? '权限详情' : '编辑权限'
  dialogData.disabled = disabled
  let pname = '主类目'
  let ptype = ENUM_AUTH_TYPE['目录']
  if (row.pid == 0) {
    pname = '主类目'
    ptype = ENUM_AUTH_TYPE['目录']
  } else {
    const pData = menuList.find((item) => item.id == row.pid)
    pname = pData?.title ?? ''
    ptype = pData?.type ?? ENUM_AUTH_TYPE['目录']
  }
  AuthInfoRef.value?.init({ ...row, pname, pid: row.pid, ptype })
}
/**
 * 点击删除
 */
function delClick(scoped: any) {
  useNotic().confirm(`您确定要删除<${scoped.row.title}>吗？`, (flag) => {
    if (flag) {
      authApi.delAuth(scoped.row).then((res) => {
        if (res.success) {
          useNotic().success('删除成功')
          getDataList()
        }
      })
    }
  })
}
/**
 * 表格切换全部展开、收起状态
 */
function changeExpendClick(isExpand: boolean) {
  tableRef.value?.setAllRowExpansion(tableData.data, isExpand)
}
/**
 * 获取表格数据
 */
function getDataList() {
  const menuTree: any[] = []
  authApi.getAuthList().then((res) => {
    menuList = res.data.data || []
    menuList.forEach((menu: any) => {
      // 根目录
      if (menu.pid == 0) {
        menuTree.push(menu)
      }
      // 子目录
      else {
        for (let item of menuList) {
          if (menu.pid == item.id) {
            if (!item.children) {
              item.children = []
            }
            item.children.push(menu)
            break
          }
        }
      }
    })
    tableData.data = menuTree
  })
}
</script>

<template>
  <dui-page>
    <template #btn>
      <db-auth-btn :auth="ENUM_BTN_AUTH_SYS['权限:增']" type="primary" iconType="add" @click="addClick"> 添加权限 </db-auth-btn>
      <el-button type="primary" :icon="IconFold" @click="changeExpendClick(false)">全部收起</el-button>
      <el-button type="primary" :icon="IconExpand" @click="changeExpendClick(true)">全部展开</el-button>
    </template>
    <template #default>
      <dui-table
        ref="tableRef"
        :data="tableData.data"
        :columns="tableData.columns"
        :total="tableData.total"
        :search="tableData.search"
        :isPagination="false"
        row-key="id"
      >
        <template #handleSlot="scoped">
          <dui-action :list="setBtnList(scoped)" />
        </template>
      </dui-table>
      <!-- 弹窗 -->
      <AuthInfo ref="AuthInfoRef" v-bind="dialogData" @refresh="getDataList" />
    </template>
  </dui-page>
</template>
